package org.example.teachermall04.controller;

import org.example.teachermall04.dto.CarItem;
import org.example.teachermall04.entity.Address;
import org.example.teachermall04.entity.Users;
import org.example.teachermall04.service.AddressService;
import org.example.teachermall04.service.OrderService;
import org.example.teachermall04.service.ShopcarService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopcarService shopcarService;
    @Autowired
    private AddressService addressService;

    @GetMapping("/orders")
    public String orders(Model model) {
        return "orders";
    }

    @PostMapping("/order/submit")
    public String submit(Integer addressId,String payType,Model model,HttpSession session) {
        Users user = (Users)session.getAttribute("loginUser");
        if(user == null) {
            return "login";
        }
        Integer userId = user.getId();
        //拿到新订单编号
        String OrderNo = orderService.submitOrder(userId,addressId,user.getTelphone(),payType,session);
        //拿到总金额以及支付类型
        Double totalPrice = shopcarService.getTotalPrice(userId);
        model.addAttribute("OrderNo", OrderNo);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("payType",payType);
        return "order_submit";
    }

    @GetMapping("/order/add")
    public String addOrder(Model model, HttpSession session) {
        Users user = (Users)session.getAttribute("loginUser");
        if(user==null){
            return "login";
        }
        //获取地址列表、购物车数据、购物车总价格
        //1. 地址列表
        List<Address> addresses = addressService.getAllAddresses(user.getId());
        //2. 购物车数据
        List<CarItem> carItems = shopcarService.getCar(user.getId());
        //3. 获取总价格
        Double totalPrice = shopcarService.getTotalPrice(user.getId());
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("carItems", carItems);
        model.addAttribute("addresses", addresses);


        return "order_add";
    }
}
